package com.fyl.pattern.singleton.demo7;

import java.io.*;

/**
 * 测试使用序列化破坏单例模式
 */
public class Client {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        writeObject2File();
        readObjectFromFile();
        readObjectFromFile();

    }
    //向文件中写数据
    public static void writeObject2File() throws IOException {
        //1.获取singleton对象
        Singleton singleton = Singleton.getInstance();
        //2.创建对象输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\13037\\Desktop\\a.txt"));
        //3.写
        oos.writeObject(singleton);
        //4.释放资源
        oos.close();
    }
    //从文件中读取数据
    public static void readObjectFromFile() throws IOException, ClassNotFoundException {
        //创建对象输入流
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\13037\\Desktop\\a.txt"));
        //读取
        Singleton instance = (Singleton) ois.readObject();
        System.out.println("instance = " + instance);
        //释放资源
        ois.close();
    }
}
